package com.neusoft.aspect;

import com.neusoft.entity.LogEntity;
import com.neusoft.entity.UsersEntity;
import com.neusoft.mapper.LogMapper;
import com.neusoft.utils.UserUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class LogAspect {

    @Resource
    LogMapper logMapper;

    @Pointcut("execution(* com.neusoft.controller..*.*(..))")
    public void pointcut(){

    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        UsersEntity loginUser = UserUtils.getLoginUser();
        String operator = "匿名用户";
        if(loginUser != null){
            operator = loginUser.getUsername();
        }

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取请求url
        String url = request.getRequestURL().toString();
        // 获取请求ip
        String ip = request.getRemoteAddr();
        String req_method = request.getMethod();
        Signature signature = joinPoint.getSignature();
        String method_name = signature.getName();
        LogEntity logEntity = new LogEntity();
        logEntity.setUrl(url);
        logEntity.setIp(ip);
        logEntity.setMethodName(method_name);
        logEntity.setOperator(operator);
        logEntity.setReqMethod(req_method);
        logMapper.insert(logEntity);
    }
}
